package com.nb.linkedlist;

/**
 * @author lihaoyang
 * @date 2021/12/29
 */
public class MergeSortedLinkedList {

    public static void main(String[] args) {

        MyNode nodeA1 = new MyNode(2);
        MyNode nodeA2 = new MyNode(5);
        MyNode nodeA3 = new MyNode(7);
        nodeA1.next=nodeA2;
        nodeA2.next=nodeA3;

        MyNode nodeB1 = new MyNode(3);
        MyNode nodeB2 = new MyNode(6);
        MyNode nodeB3 = new MyNode(8);
        nodeB1.next=nodeB2;
        nodeB2.next=nodeB3;

        printNode(nodeA1);
        printNode(nodeB1);
        nodeA1 = mergeSortedLinkedList2(nodeA1,nodeB1);
        printNode(nodeA1);
    }


    public static MyNode mergeSortedLinkedList(MyNode a,MyNode b){
       MyNode headA = new MyNode(null);
       headA.next=a;
       MyNode pre = headA;
       while(a!=null && b!=null){
           if(a.value!=null&&b.value!=null){
               if(a.value <=b.value){
                   pre=a;
                   a=a.next;
               }else {
                   MyNode bNext = b.next;
                   pre.next=b;
                   b.next=a;
                   pre=b;
                   b=bNext;
               }
           }

       }
       if(b!=null){
           pre.next=b;
       }
       return headA.next;
    }



    public static MyNode mergeSortedLinkedList2(MyNode a,MyNode b){
        MyNode head = new MyNode(null);
        while(a!=null && b!=null){
            if(a.value!=null&&b.value!=null){
                if(a.value <=b.value){
                    head.next = a;
                    a=a.next;

                }else {
                    head.next=b;
                    b=b.next;
                }
                head = head.next;
            }

        }
        if(b!=null){
            head.next=b;
        }
        if(a!=null){
            head.next=a;
        }
        return head;
    }
    public static void printNode(MyNode node){
        if(node == null){
            return;
        }
        while (node != null){
            System.out.print(node.getValue()+" -> ");
            node = node.getNext();
        }
        System.out.println();
    }
}
